<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            * {
                padding: 0;
                margin: 0;
            }
            img {
                width: 100%;
                height: 183px;
            }
        </style>
    </head>
    <body>
        <div class="img-container"><img src="./img/loading.gif" data-src="./img/1.jpg" alt="" /></div>
        <div class="img-container"><img src="./img/loading.gif" data-src="./img/2.jpg" alt="" /></div>
        <div class="img-container"><img src="./img/loading.gif" data-src="./img/3.jpg" alt="" /></div>
        <div class="img-container"><img src="./img/loading.gif" data-src="./img/4.jpg" alt="" /></div>
        <div class="img-container"><img src="./img/loading.gif" data-src="./img/5.jpg" alt="" /></div>
        <div class="img-container"><img src="./img/loading.gif" data-src="./img/6.jpg" alt="" /></div>
        <div class="img-container"><img id="img1" src="./img/loading.gif" data-src="./img/7.jpg" alt="" /></div>
    </body>
    <script>
        // 解构赋值：把类数组转成数组，方便下面图片数组中已加载图片的删除
        var imgArray = [...document.querySelectorAll("img")];
        // 加载图片判断方法
        function lazyLoad() {
            // 每次滑动，循环剩余图片元素数组
            for (let i = 0; i < imgArray.length; i++) {
                // 判断元素是否在视口范围内
                if (inView(imgArray[i])) {
                    // 如果与视口产生交集，就把地址属性赋值给src
                    imgArray[i].src = imgArray[i].dataset.src;
                    // 把加载后的图片从数组中去掉，避免已加载图片在滑动后的的二次重复计算
                    imgArray.splice(i--, 1);
                }
            }
        }
        // 判断元素框有无进入窗口/视口
        function inView(objImg) {
            // 获取元素得视口属性方法:element.getBoundingClientRect();
            const elementImg = objImg.getBoundingClientRect();
            return elementImg.bottom > 0 && elementImg.top < window.innerHeight;
        }
        // 首次加载一次
        lazyLoad();
        // 滑动时加载图片
        window.onscroll = lazyLoad;

    </script>
</html>
